package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.SeckillConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.service.UpSeckillScheduleService;
import com.atguigu.gulimall.seckill.to.SeckillSessionTo;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.to.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UpSeckillScheduleServiceImpl implements UpSeckillScheduleService {

    @Autowired
    CouponFeignService couponFeignService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

   // 引入 redisson分布式锁
    @Autowired
    RedissonClient redissonClient;


    @Override
    public void upSeckillRecentThreeDay() {
        R lates3DaySession = couponFeignService.getLates3DaySession();
         //取出 远程调用结果做缓存
        if(lates3DaySession.getCode()==0){
            List<SeckillSessionTo> data = lates3DaySession.getData(new TypeReference<List<SeckillSessionTo>>() {});
            // 商品做缓存
            if(data!=null&&data.size()>0){
                cacheSeckillSession(data);
                cacheSeckillSessionRelation(data);
            }
        }

    }


    // 给 活动场次关联 商品做缓存  对数据进行操作没有返回值 就用 foreach  不用
    private void cacheSeckillSessionRelation(List<SeckillSessionTo> data) {
     data.stream().forEach((session)->{
         // 取出场次所有关联的 秒杀商品的信息
         BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(SeckillConstant.CACHE_SECKILL_SESSIONRELATION_PREFIX + session.getId());
         session.getSeckillSessionRelationToList().stream().forEach((sessionRelationSku)->{
            // 获取 商品的秒杀信息 和 商品详情信息
             SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
             //获取商品的详情信息
             R info = productFeignService.info(sessionRelationSku.getSkuId());
             if(info.getCode()==0){
                 SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                 });
                 seckillSkuRedisTo.setSkuInfo(skuInfo);
             }

             // 先把 关联的商品秒杀信息 复制过去
             BeanUtils.copyProperties(sessionRelationSku,seckillSkuRedisTo);
             // 给商品设置 秒杀随机号
             String random = UUID.randomUUID().toString().replace("-", "");
             seckillSkuRedisTo.setRandomCode(random);

              //给每一件商品设置 信号量  引入分布式锁
             RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.CACHE_SECKILL_SESSIONSEMAPHORE_PREFIX + random);
             // 每一件商品的信号量为 该秒杀商品的库存数   商品的秒杀数量 控制访问量
             semaphore.trySetPermits(sessionRelationSku.getSeckillCount().intValue());

             // 在hash结构中存入 每一件商品的对应的 秒杀商品信息 以及商品详情信息
             String jsonString = JSON.toJSONString(seckillSkuRedisTo);
             hashOps.put(sessionRelationSku.getSkuId(),jsonString);
         });
     });



    }


    // 给 活动场次做缓存
    private void cacheSeckillSession(List<SeckillSessionTo> data) {
        //先取出 每一场次
        data.stream().forEach(session->{
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();

            String sessionRedisKey= SeckillConstant.CACHE_SECKILL_SESSION_PREFIX+startTime+"_"+endTime;

            Boolean aBoolean = stringRedisTemplate.hasKey(sessionRedisKey);

            List<String> collect = session.getSeckillSessionRelationToList().stream()
                    .map((sessionRelation) -> sessionRelation.getPromotionId() + "_" + sessionRelation.getSkuId().toString())
                    .collect(Collectors.toList());
            stringRedisTemplate.opsForList().leftPushAll(sessionRedisKey,collect);
        });
    }


}
